﻿using System;

namespace BDRUtils.Extensions
{
    public static class DatetimeExtensions
    {
        // 本地时区 1970.1.1格林威治时间
        public static DateTime Greenwich_Mean_Time = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);

        /// <summary>
        /// 标准日期 .ToString("yyyy-MM-dd")
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToDateStandardString(this DateTime dt) => dt.ToString("yyyy-MM-dd");

        /// <summary>
        /// 标准时间 .ToString("yyyy-MM-dd HH:mm:ss")
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToDateTimeStandardString(this DateTime dt) => dt.ToString("yyyy-MM-dd HH:mm:ss");

        /// <summary>
        /// 标准时间(带毫秒) .ToString("yyyy-MM-dd HH:mm:ss.fff")
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToDateTimeString(this DateTime dt) => dt.ToString("yyyy-MM-dd HH:mm:ss.fff");

        /// <summary>
        /// 10位时间戳转化为时间类型
        /// </summary>
        /// <param name="ticks"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeFromTenUnix(this long ticks) => (ticks * 1000).ToDateTimeFromUnix();

        /// <summary>
        /// 13位时间戳转化为时间类型
        /// </summary>
        /// <param name="ticks"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeFromUnix(this long ticks) => new DateTime(Greenwich_Mean_Time.Ticks + ticks * 10000).ToLocalTime();

        /// <summary>
        /// 时间类型转化为时间戳(13位)
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static long ToUnixDateTime(this DateTime dt)
        {
            long val = 0;
            try
            {
                // 除以10000，保持13位
                val = (dt.ToUniversalTime().Ticks - Greenwich_Mean_Time.Ticks) / 10000;
            }
            catch { }
            return val;
        }

        /// <summary>
        /// 字符串转化为时间类型
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime? ToDateTime(this string value)
        {
            if (value.IsNullOrWhiteSpace() || !DateTime.TryParse(value, out DateTime result))
                return null;

            return result;
        }

    }
}
